<template>
  <el-upload
    ref="fileupload"
    class="upload-demo"
    action="#"
    :http-request="uploadFile"
    :before-upload="beforeUploadFile"
    :on-success="onUploadFileSuccess"
    :on-error="onUplodeFileError"
    :on-change="handleChange"
    multiple
    :show-file-list="false"
    :file-list="fileList"
    :limit="5"
    :on-exceed="handleExceed"
  >
    <el-button icon="el-icon-tickets" size="middle">导入勘探点</el-button>
  </el-upload>
</template>

<script>
// 附件上传
import { explorationImportData } from '@/api/projectManage/project/exploration'
export default {
  name: 'FileUpload',
  components: {
  },
  props: {

  },
  data() {
    return {
      fileList: [] // 存放编辑 文件的集合（附件回显）
    }
  },
  mounted() {
  },
  methods: {
    // 附件上传之前调用的函数，控制附件上传的大小和格式
    beforeUploadFile(file) {
      const isLt30M = file.size / 1024 / 1024 < 30
      if (!isLt30M) {
        this.msgError('上传文件大小不能超过 30MB!')
        return false
      }
      return true
    },
    // 自定义文件上传
    uploadFile(item) {
      // 传入文件的类型
      const proId = this.$store.state.basicInfo.proId
      const formData = new FormData()
      formData.append('file', item.file)
      explorationImportData(proId, formData)
        .then(res => {
          item.onSuccess(res)
        })
        .catch(err => {
          item.onError(err)
        })
    },
    // 上传的文件改变时调用的方法，附件新增 附件删除都会调用
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    // 上传成功的回调
    onUploadFileSuccess(res, file) {
      if (res) {
        this.$parent.getList()
        this.msgSuccess('上传成功')
      } else {
        this.msgError(res.message)
      }
    },
    // 限制文件上传的个数
    handleExceed(files, fileList) {
      this.msgWarning(
        `当前限制选择 5 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    // 文件上传失败的回调
    onUplodeFileError(err, file, fileList) {
      if (err.message === 'Network Error') this.msgError('上传文件失败')
    }
  }
}
</script>

<style lang="scss">
  .upload-demo{
    display: inline-block;
  }
  .el-upload__tip{
    padding-left:10px;
    color:red;
    font-size: 12px
  }
</style>
